/**
 * AI换脸功能相关处理
 */
document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const templateItems = document.querySelectorAll('.template-item');
    const templateSelected = document.querySelector('.template-selected');
    const selectedTemplateImg = document.getElementById('selectedTemplateImg');
    const changeTemplateBtn = document.getElementById('changeTemplateBtn');
    const faceSwapUploadBox = document.getElementById('faceSwapUploadBox');
    const facePhotoInput = document.getElementById('facePhotoInput');
    const facePreviewImage = document.getElementById('facePreviewImage');
    const previewBox = faceSwapUploadBox?.nextElementSibling;
    const processBtn = document.getElementById('processBtn');
    const resetBtn = document.getElementById('resetFaceSwapBtn');
    const downloadBtn = document.getElementById('downloadFaceSwapBtn');
    const resultPreview = document.getElementById('resultPreview');
    const faceSwapResult = document.getElementById('faceSwapResult');
    const loadingOverlay = document.querySelector('.loading-overlay');
    
    // 为亮度、对比度和磨皮强度滑块添加显示值的功能
    const brightnessSlider = document.getElementById('brightnessSlider');
    const contrastSlider = document.getElementById('contrastSlider');
    const smoothnessSlider = document.getElementById('smoothnessSlider');
    const brightnessValue = document.getElementById('brightnessValue');
    const contrastValue = document.getElementById('contrastValue');
    const smoothnessValue = document.getElementById('smoothnessValue');

    // AI换脸功能的状态管理
    const state = {
        selectedTemplate: null,
        userPhoto: null,
        processing: false
    };

    // 参数调整默认值
    const defaultParams = {
        brightness: 100,
        contrast: 100,
        smoothness: 50
    };
    
    // 模板选择
    templateItems.forEach(item => {
        item.addEventListener('click', () => {
            // 移除所有模板的选中状态
            templateItems.forEach(template => template.classList.remove('selected'));
            // 设置当前模板选中
            item.classList.add('selected');
            
            // 保存选中的模板信息
            const templateId = item.dataset.template;
            const templateImgSrc = item.querySelector('img').src;
            state.selectedTemplate = {
                id: templateId,
                src: templateImgSrc
            };
            
            // 显示已选模板区域
            if (templateSelected && selectedTemplateImg) {
                selectedTemplateImg.src = templateImgSrc;
                templateSelected.classList.remove('hidden');
            }
            
            // 如果用户已上传照片，则启用处理按钮
            if (state.userPhoto && processBtn) {
                processBtn.disabled = false;
            }
        });
    });
    
    // 更换模板按钮
    if (changeTemplateBtn) {
        changeTemplateBtn.addEventListener('click', () => {
            templateSelected.classList.add('hidden');
            // 重置模板选择状态
            templateItems.forEach(template => template.classList.remove('selected'));
            state.selectedTemplate = null;
            
            // 禁用处理按钮
            if (processBtn) {
                processBtn.disabled = true;
            }
        });
    }

    // 绑定拖拽上传相关事件
    if (faceSwapUploadBox) {
        faceSwapUploadBox.addEventListener('dragover', (e) => {
            e.preventDefault();
            faceSwapUploadBox.classList.add('drag-over');
        });

        faceSwapUploadBox.addEventListener('dragleave', () => {
            faceSwapUploadBox.classList.remove('drag-over');
        });

        faceSwapUploadBox.addEventListener('drop', (e) => {
            e.preventDefault();
            faceSwapUploadBox.classList.remove('drag-over');
            const file = e.dataTransfer.files[0];
            handlePhotoUpload(file);
        });

        faceSwapUploadBox.addEventListener('click', () => {
            if (facePhotoInput) {
                facePhotoInput.click();
            }
        });
    }

    // 点击上传
    if (facePhotoInput) {
        facePhotoInput.addEventListener('change', () => {
            const file = facePhotoInput.files[0];
            handlePhotoUpload(file);
        });
    }

    /**
     * 处理照片上传
     * @param {File} file - 上传的图片文件
     */
    function handlePhotoUpload(file) {
        if (!file || !file.type.startsWith('image/')) {
            alert('请上传有效的图片文件！');
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            state.userPhoto = e.target.result;
            
            if (facePreviewImage && previewBox) {
                facePreviewImage.src = e.target.result;
                faceSwapUploadBox.classList.add('hidden');
                previewBox.classList.remove('hidden');
            }

            // 如果已选择模板，则启用处理按钮
            if (state.selectedTemplate && processBtn) {
                processBtn.disabled = false;
            }
        };
        reader.readAsDataURL(file);
    }

    /**
     * 更新预览图
     * @param {Object} params - 处理参数
     */
    function updatePreview(params) {
        if (!state.userPhoto || !state.selectedTemplate) return;
        
        // 显示加载动画
        if (loadingOverlay) {
            loadingOverlay.classList.remove('hidden');
        }

        // 模拟AI处理延迟
        setTimeout(() => {
            console.log('应用参数:', params);
            console.log('处理模板:', state.selectedTemplate.id);
            
            // 这里模拟换脸处理结果，实际应用中需要调用后端API
            if (faceSwapResult && resultPreview) {
                // 使用用户照片作为结果（实际应用中这里应该是API返回的处理后图片）
                faceSwapResult.src = state.userPhoto;
                resultPreview.classList.remove('hidden');
                if (downloadBtn) {
                    downloadBtn.classList.remove('hidden');
                }
            }
            
            if (loadingOverlay) {
                loadingOverlay.classList.add('hidden');
            }
        }, 2000);
    }

    // 初始化滑动条控件
    function initializeSliders() {
        if (brightnessSlider && brightnessValue) {
            brightnessSlider.addEventListener('input', (e) => {
                brightnessValue.textContent = `${e.target.value}%`;
                updateParamPreview();
            });
        }
        
        if (contrastSlider && contrastValue) {
            contrastSlider.addEventListener('input', (e) => {
                contrastValue.textContent = `${e.target.value}%`;
                updateParamPreview();
            });
        }
        
        if (smoothnessSlider && smoothnessValue) {
            smoothnessSlider.addEventListener('input', (e) => {
                smoothnessValue.textContent = `${e.target.value}%`;
                updateParamPreview();
            });
        }
    }
    
    function updateParamPreview() {
        if (!state.userPhoto || !state.selectedTemplate) return;
        if (!faceSwapResult || faceSwapResult.src === '') return;
        
        // 获取当前参数值
        const params = {
            brightness: brightnessSlider ? parseInt(brightnessSlider.value) : defaultParams.brightness,
            contrast: contrastSlider ? parseInt(contrastSlider.value) : defaultParams.contrast,
            smoothness: smoothnessSlider ? parseInt(smoothnessSlider.value) : defaultParams.smoothness
        };
        
        // 实际应用中，这里应该根据参数重新调用API进行图像处理
        console.log('更新参数预览:', params);
    }

    // 处理按钮点击事件
    if (processBtn) {
        processBtn.addEventListener('click', () => {
            if (!state.processing) {
                state.processing = true;
                const params = {
                    brightness: brightnessSlider ? parseInt(brightnessSlider.value) : defaultParams.brightness,
                    contrast: contrastSlider ? parseInt(contrastSlider.value) : defaultParams.contrast,
                    smoothness: smoothnessSlider ? parseInt(smoothnessSlider.value) : defaultParams.smoothness
                };
                updatePreview(params);
            }
        });
    }

    // 重置按钮
    if (resetBtn) {
        resetBtn.addEventListener('click', () => {
            // 重置状态
            state.userPhoto = null;
            state.processing = false;
            
            // 重置UI
            if (faceSwapUploadBox) faceSwapUploadBox.classList.remove('hidden');
            if (previewBox) previewBox.classList.add('hidden');
            if (resultPreview) resultPreview.classList.add('hidden');
            if (processBtn) processBtn.disabled = true;
            if (downloadBtn) downloadBtn.classList.add('hidden');
            
            // 重置输入
            if (facePhotoInput) facePhotoInput.value = '';
            
            // 重置滑块
            if (brightnessSlider) {
                brightnessSlider.value = defaultParams.brightness;
                brightnessValue.textContent = `${defaultParams.brightness}%`;
            }
            if (contrastSlider) {
                contrastSlider.value = defaultParams.contrast;
                contrastValue.textContent = `${defaultParams.contrast}%`;
            }
            if (smoothnessSlider) {
                smoothnessSlider.value = defaultParams.smoothness;
                smoothnessValue.textContent = `${defaultParams.smoothness}%`;
            }
        });
    }

    // 下载处理后的图片
    if (downloadBtn) {
        downloadBtn.addEventListener('click', () => {
            if (!faceSwapResult || !faceSwapResult.src) return;
            
            // 创建临时链接下载图片
            const link = document.createElement('a');
            link.download = 'face-swap-result.jpg';
            link.href = faceSwapResult.src;
            link.click();
        });
    }

    // 初始化滑动条控件
    initializeSliders();
});